<?php
require_once("{$CfgPara->root}/class/mysql.func.php");

/**
 * comment 评论数据模型
 *
 * @version 1.0
 * @author Human
 */
class comment_m
{
    const CommentType_Work = 1;

    const CommentType_ShoeShow = 2;

    public $commentTable;
    public $parentIdColumn;
    public $parentTable;

    public function __construct($dbPara = NULL)
    {
        if ($dbPara != null) {
            db_connect($dbPara);
        }
    }

    /**
     * 获取评论列表 成功返回评论对象数组 错误返回错误信息
     * @param int $id 作品或鞋主秀id
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     * @param int $page 当前页
     * @param int $page_size 每页条目数
     * @param int $desc 是否倒序，1倒序
     */
    public function comment_list($id, $type, $page, $page_size, $desc = 0)
    {
        if (!is_numeric($id) || !is_numeric($page) || !is_numeric($page_size)) {
            return "错误:评论查询信息错误";
        }
        $this->get_type_table($type);
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        $sql_str = "SELECT `{$this->commentTable}`.*,date_format(`{$this->commentTable}`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName 
                    FROM `{$this->commentTable}`, `users` 
                    WHERE `{$this->commentTable}`.`{$this->parentIdColumn}` = {$id} AND `users`.`Id` = `{$this->commentTable}`.`UserId` 
                    ORDER BY `{$this->commentTable}`.`Id` ";
        if ($desc == 1) {
            $sql_str .= 'DESC ';
        }
        $sql_str .= "LIMIT {$limit_offset},{$page_size}";
        $result1 = db_query($sql_str);
        if ($result1 instanceof mysqli_result) {
            $fetch_result = db_fetch_list($result1, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 获取评论类型所在的数据表与字段
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     */
    public function get_type_table($type)
    {
        if ($type == comment_m::CommentType_Work) {
            $this->commentTable = 'works_comment';
            $this->parentIdColumn = 'WorkId'; //作品Id所在的列名
            $this->parentTable = 'works';
        } else {
            $this->commentTable = 'show_comment';
            $this->parentIdColumn = 'ShowId'; //鞋主秀Id所在的列名
            $this->parentTable = 'shoe_show';
        }
    }

    /**
     * 获取单个评论信息 成功返回评论对象 错误返回错误信息
     * @param int $comment_id 评论Id
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     */
    public function comment_msg($comment_id, $type)
    {
        if (!is_numeric($comment_id) || !is_numeric($type)) {
            return "错误:评论查询信息错误";
        }
        $this->get_type_table($type);
        $sql_str = "SELECT `{$this->commentTable}`.*,date_format(`{$this->commentTable}`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName 
                    FROM `{$this->commentTable}`, `users` 
                    WHERE `{$this->commentTable}`.`Id` = '{$comment_id}' AND `users`.`Id` = `{$this->commentTable}`.`UserId`";
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            if ($msg = $result->fetch_object()) {
                return $msg;
            } else {
                return '获取评论信息失败';
            }
        } else {
            return db_error();
        }
    }

    /**
     * 评论的回复列表 成功返回评论对象数组 错误返回错误信息
     * @param int $comment_id 评论Id
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     * @param int $view_type 查看类型 0精简 仅用户名和内容 1完整 像评论一样
     * @param int $findCount (引用)总回复数 错误为-1
     * @param int $limit 限制查询数量 0为不限制
     * @param int $desc 是否倒序，1倒序
     */
    public function comment_reply_list($comment_id, $type, $view_type, &$find_count, $limit = 0, $desc = 0)
    {
        if (!is_numeric($comment_id) || !is_numeric($limit)) {
            return "错误:评论回复查询信息错误";
        }
        $this->get_type_table($type);
        if ($view_type == 0) //精简样式
        {
            $sql_str = "SELECT SQL_CALC_FOUND_ROWS `$this->commentTable`.`Text`,`$this->commentTable`.`AtUserName`,`users`.`Name` as UserName 
                        FROM `$this->commentTable`, `users` 
                        WHERE `$this->commentTable`.`ReplyId` = '{$comment_id}' AND `users`.`Id` = `$this->commentTable`.`UserId` 
                        ORDER BY `$this->commentTable`.`Id` ";
        } else {
            $sql_str = "SELECT SQL_CALC_FOUND_ROWS `$this->commentTable`.*,date_format(`$this->commentTable`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName 
                        FROM `$this->commentTable`, `users` 
                        WHERE `$this->commentTable`.`ReplyId` = '{$comment_id}' AND `users`.`Id` = `$this->commentTable`.`UserId` 
                        ORDER BY `$this->commentTable`.`Id` ";
        }
        if ($desc == 1) {
            $sql_str .= 'DESC ';
        }
        if ($limit > 0) {
            $sql_str .= "LIMIT {$limit}";
        }
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            $found_count_result = db_query('SELECT FOUND_ROWS()');
            if ($found_count_result !== false) {
                $find_count = $found_count_result->fetch_array()[0];
            } else {
                $find_count = -1;
            }
            $fetch_result = db_fetch_list($result, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 评论保存 成功返回当前作品(鞋主秀)评论数 评论数获取错误时返回'-1' 错误返回错误信息
     * @param int $id 作品Id
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     * @param int $reply_id 本评论回复的对象id 为0直接发表
     * @param string $at_username 需要@的人的用户名
     */
    public function comment_save($id, $type, $reply_id, $comment, $at_username)
    {
        if (!is_numeric($id) || !is_numeric($reply_id) || !is_numeric($type)) {
            return "错误:评论保存信息错误";
        }
        $this->get_type_table($type);
        $c = urldecode($comment);
        $c = db_escape($c);
        //20170119 添加 评论需要回复@的用户名 当前仅在评论的详细页面中的灰色列表中的回复才有
        $at = urldecode($at_username);
        $at = db_escape($at);

        if (mb_strlen($c, 'utf8') > 135) {
            return "错误:提交的评论长度超过135字符";
        }
        if ($c !== false) {
            $msg_result = db_query(
                "SELECT `$this->parentTable`.`Author`,`$this->parentTable`.`CommentCount`
                 FROM $this->parentTable
                 WHERE `$this->parentTable`.`Id` = {$id} AND `$this->parentTable`.`State` = 1");
            if ($msg_result === false) {
                return db_rollback();
            }
            if ($msg_result->num_rows <= 0 ||
                !($msg = $msg_result->fetch_object())
            ) //没有获得作品信息
            {
                return "错误:无法获取此作品信息,如果此作品为草稿,无法评论";
            }
            db_begin();
            $result = db_query("INSERT INTO `$this->commentTable` 
                                          SET 
                                          `{$this->parentIdColumn}` = '{$id}',
                                          `UserId` = '{$_SESSION['user_id']}',
                                          `ReplyId` = '{$reply_id}',
                                          `Text` = '{$c}',
                                          `AtUserName` = '{$at}'");
            if ($result !== true) return db_rollback();

            $comment_id = db_insert_id();
            $comment_count = $msg->CommentCount + 1;

            //推送消息到作者
            $sql_str = "INSERT INTO `message_comment` 
                        SET `Type` = 1,`MsgIdFrom` = {$comment_id},`UserId`={$msg->Author}";
            $result = db_query($sql_str);
            if ($result !== true) return db_rollback();

            //20170119 添加 推送消息到回复的评论作者
            if ($reply_id > 0) //回复的id>0代表此条评论为回复信息
            {
                //获取回复的评论的评论信息
                $sql_str = "SELECT {$this->commentTable}.UserId, users.Name as UserName
                            FROM $this->commentTable,users 
                            WHERE {$this->commentTable}.Id = {$reply_id} AND {$this->commentTable}.UserId = users.Id";
                $comment_msg_result = db_query($sql_str);
                if ($comment_msg_result === false) return db_rollback();
                if ($comment_msg_result->num_rows <= 0 ||
                    !($comment_msg = $comment_msg_result->fetch_object())
                ) //没有获得回复的对象
                {
                    db_rollback();
                    return "错误:无法获取回复的对象";
                }
                // 如果需要回复的评论作者不是作品作者 测试时可注释掉if 
                //if ($comment_msg->UserId != $msg->Author) 
                //{
                //推送消息到需要回复的评论的作者
                $sql_str = "INSERT INTO `message_comment` 
                                SET `Type` = 3,`MsgIdFrom` = {$comment_id},`UserId` = {$comment_msg->UserId}";
                $result = db_query($sql_str);
                if ($result !== true) return db_rollback();
                //更新需要回复的评论的作者的推送消息数
                $sql_str = "UPDATE `message_count` 
                                SET `Comment` = `Comment` + 1,
                                    `AllComment` = `AllComment` + 1
                                WHERE `UserId` = {$comment_msg->UserId}";
                $result = db_query($sql_str);
                if ($result !== true) return db_rollback();
                //if ($comment_msg->UserName != $at_username) //如果回复需要@的人不是回复的人
                //{
                if ($at_username != '') //需要@的人
                {
                    //获取@的人的id
                    $sql_str = "SELECT Id FROM users WHERE Name = '{$at_username}'";
                    $result = db_query($sql_str);
                    if ($result === false) return db_rollback();
                    if ($result->num_rows <= 0 ||
                        !($atuser_msg = $result->fetch_object())
                    ) //没有获得回复的对象
                    {
                        db_rollback();
                        return "错误:无法获取要回复人的id";
                    }
                    //推送消息到需要@的人
                    $sql_str = "INSERT INTO `message_comment` 
                                        SET `Type` = 5,`MsgIdFrom` = {$comment_id},`UserId` = $atuser_msg->Id";
                    $result = db_query($sql_str);
                    if ($result !== true) return db_rollback();
                    //更新需要回复的评论的作者的推送消息数
                    $sql_str = "UPDATE `message_count` 
                                        SET `Comment` = `Comment` + 1,
                                            `AllComment` = `AllComment` + 1 
                                        WHERE `UserId` = {$comment_msg->UserId}";
                    $result = db_query($sql_str);
                    if ($result !== true) return db_rollback();
                }
                //}
                //}
            }

            //更新作品的评论数、作者被评论的总数以及作者评论的推送消息数
            $result = db_query("UPDATE `users`,`$this->parentTable`,`message_count` SET 
                                            `$this->parentTable`.`CommentCount` = {$comment_count} ,
                                            `users`.`CommentCount` = `users`.`CommentCount` + 1,
                                            `message_count`.`Comment` = `message_count`.`Comment` + 1,
                                            `message_count`.`AllComment` = `message_count`.`AllComment` + 1
                                            WHERE `$this->parentTable`.`Id` = {$id} AND 
                                            `users`.`Id` = {$msg->Author} AND 
                                            `message_count`.`UserId` = {$msg->Author}");

            if ($result !== true) return db_rollback();
            // 20170125 删除 评论不再做操作记录
            //$op = new user_operate();
            //$op->operate_save($op::WorkCommend, $_SESSION['user_id'], $comment_id);
            // 20170125 修改 只有当评论为作品时，才记录热门统计表
            //评论信息插入成功 则插入热门统计表
            if ($type == comment_m::CommentType_Work) {
                $result = db_query("INSERT INTO `works_hot_1` 
                                                SET `WorkId` = {$id},
                                                    `OpType` = 2");
                if ($result !== true) return db_rollback();
                $result = db_query("INSERT INTO `works_hot_2` 
                                                SET `WorkId` = {$id},
                                                    `OpType` = 2");
            }
            db_commit();
            return (string)$comment_count;
        } else {
            return "错误:评论的文本不合法";
        }
    }

    /**
     * 评论点赞 成功返回1 取消点赞返回-1 错误返回错误信息
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     * @param int $comment_id 评论Id
     */
    public function comment_up($type, $comment_id)
    {
        if (!is_numeric($comment_id)) {
            return "错误:评论点赞信息提交错误";
        }
        $this->get_type_table($type);
        $result = 1;
        $update_type = '+';
        db_begin();
        $result1 = db_query("INSERT INTO `{$this->commentTable}_up` SET 
                                        `CommentId` = '{$comment_id}',
                                        `UserId` = '{$_SESSION['user_id']}'");

        if ($result1 !== true) {
            if (db_errno() === 1062) //已经赞过 则取消点赞
            {
                $result = -1;
                $update_type = '-';
                $result2 = db_query("DELETE FROM `{$this->commentTable}_up` WHERE 
                                                `CommentId` = '{$comment_id}' AND
                                                `UserId` = '{$_SESSION['user_id']}'");
                if ($result2 !== true) {
                    return db_rollback();
                }
            } else {
                return db_rollback();
            }
        }
        //更新评论的点赞数
        $result3 = db_query("UPDATE `{$this->commentTable}` SET `UpCount` = `UpCount` {$update_type} 1 
                                                    WHERE `Id` = {$comment_id}");
        if ($result3 !== true) {
            return db_rollback();
        }
        db_commit();
        return $result;
    }

    /**
     * 删除评论 成功返回'1' 失败返回错误信息
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     * @param int $comment_id 评论Id
     * @param int $user_id 用户Id
     */
    public function comment_dele($type, $comment_id, $user_id)
    {
        if (!is_numeric($comment_id) || !is_numeric($user_id)) {
            return "作品评论删除时，提交的信息错误";
        }
        $this->get_type_table($type);
        $check_ok = FALSE;
        $row;
        $result_sele1 = db_query("SELECT `$this->parentTable`.`Id`,
		                                           `$this->parentTable`.`Author`,
		                                           `$this->commentTable`.`UserId`,
		                                           `$this->commentTable`.`CommentDt` 
		                                    FROM `$this->parentTable`,`$this->commentTable` 
		                                    WHERE `$this->commentTable`.`Id` = {$comment_id} AND 
		                                          `$this->parentTable`.`Id` = `$this->commentTable`.`WorkId`");
        if ($result_sele1 !== FALSE) {
            if ($row = $result_sele1->fetch_object()) {
                //作品作者和评论者可以删除
                if ($row->Author == $user_id || $row->UserId == $user_id) {
                    $check_ok = TRUE;
                }
            }
        }
        if ($_SESSION['user_level'] >= 90) { //如果为管理员可以删除
            $check_ok = TRUE;
        }
        if ($check_ok == TRUE) {
            db_begin();
            //删除评论 评论点赞、评论举报、作者的被推送的评论消息
            $result1 = db_query("DELETE FROM `$this->commentTable`
			                               WHERE `$this->commentTable`.`Id` = {$comment_id}");

            if ($result1 !== TRUE) {
                return db_rollback();
            }
            if (db_affected_rows() > 0) {
                //更新作品的评论数、作者被评论的总数
                $result2 = db_query("UPDATE `users`,`$this->parentTable` SET 
	                                            `$this->parentTable`.`CommentCount` = `$this->parentTable`.`CommentCount` - 1,
	                                            `users`.`CommentCount` = `users`.`CommentCount` - 1 
	                                            WHERE `$this->parentTable`.`Id` = {$row->Id} AND 
	                                                  `users`.`Id` = {$row->Author}");
                if ($result2 !== TRUE) {
                    return db_rollback();
                }
            }
            //删除评论点赞、评论举报、作者的被推送的评论消息
            $result3 = db_query("DELETE FROM `{$this->$commentTable}_up` WHERE `CommentId` = {$comment_id}");
            $result4 = db_query("DELETE FROM `{$this->$commentTable}_report` WHERE `CommentId` = {$comment_id}");
            $result5 = db_query("DELETE FROM `message_comment` 
                                 WHERE `Type` = 1 AND `MsgIdFrom` = {$comment_id} AND
                                       `UserId` = {$row->Author}");
            if ($result3 !== TRUE || $result4 !== TRUE || $result5 !== TRUE) {
                return db_rollback();
            }
            // 更新作者的评论消息总数
            $deleCount = db_affected_rows();
            if ($deleCount > 0) {
                $update_row = array();
                $update_row['UserId'] = $row->Author;
                $update_row['AllComment'] = "`AllComment` - {$deleCount}";
                $result6 = db_update('message_count', $update_row, 'UserId');
                if ($result6 !== true) return db_rollback();
            }

            if ($result6 !== TRUE) return db_rollback();
            //删除掉评论时间正负1秒内的热门统计 Limit1
            if ($type == comment_m::CommentType_Work) {
                $date = new DateTime($row->CommentDt);
                $i = DateInterval::createFromDateString('-1 seconds');
                $date->add($i);
                $sql_time1 = $date->format('Y-m-d H:i:s');
                $i = DateInterval::createFromDateString('+2 seconds');
                $date->add($i);
                $sql_time2 = $date->format('Y-m-d H:i:s');
                $result = db_query("DELETE FROM `works_hot_1` 
                                                WHERE `WorkId` = {$row->Id} AND 
                                                    `OpType` = 2 AND 
                                                    `OpDt` BETWEEN '{$sql_time1}' AND '{$sql_time2}' 
                                                LIMIT 1");
                if ($result != TRUE) return db_rollback();
                $result = db_query("DELETE FROM `works_hot_2`
                                                WHERE `WorkId` = {$row->Id} AND 
                                                    `OpType` = 2 AND 
                                                    `OpDt` BETWEEN '{$sql_time1}' AND '{$sql_time2}'
                                                LIMIT 1");
                if ($result != TRUE) return db_rollback();
            }
            db_commit();
            return '1';
        } else {
            return '无权限删除此评论';
        }
    }

    /**
     * 检测当前用户是否已对评论点赞
     * @param int $comment_id
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     * @return bool|string
     */
    function comment_up_check($comment_id, $type)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($comment_id)) {
            return "检查评论是否已赞时:提交的信息错误";
        }
        $this->get_type_table($type);
        $sql_str = "SELECT `CommentId` 
                    FROM `{$this->commentTable}_up` 
                    WHERE `CommentId` = {$comment_id} AND `UserId` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 评论举报 成功返回true 错误返回错误信息
     * @param int $comment_id 评论Id
     * @param int $type 评论类型 1作品 2鞋主秀 参考评论类型常数
     */
    function comment_report($comment_id, $type)
    {
        if (!is_numeric($comment_id)) {
            return "错误:评论举报信息提交错误";
        }
        $this->get_type_table($type);
        $sql_str = "INSERT INTO `{$this->commentTable}_report` 
                    SET `CommentId` = '{$comment_id}',`UserId` = '{$_SESSION['user_id']}'";
        db_query($sql_str);
        /* 20170126 删除 评论举报不需要进行操作记录
        $op = new user_operate();
        $op->operate_save($op::WorkCommentReport, $_SESSION['user_id'], $comment_id);
        */
        return true;
    }
}